package com.yc.bos.service.impl;

import com.yc.bos.dao.IRoleDao;
import com.yc.bos.dao.IUserDao;
import com.yc.bos.model.PageBean;
import com.yc.bos.model.Role;
import com.yc.bos.model.User;
import com.yc.bos.service.IUserService;
import com.yc.bos.service.base.BaseServiceImpl;
import com.yc.bos.utils.MD5Utils;
import org.activiti.engine.IdentityService;
import org.activiti.engine.impl.persistence.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

@Service
@Transactional
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private IUserDao userDao;
    @Autowired
    private IdentityService identityService;
    @Autowired
    private IRoleDao roleDao;
    @Override
    public User findByTel(String tel) {
        return null;
    }

    @Override
    public User login(String username, String password) {
        return userDao.find(username, MD5Utils.text2md5(password));
    }

    @Override
    public void modifyPassword(String newPwd, String userId) {
    /*    String hql="UPDATE User SET password=? WHERE id = ?";
        userDao.executeUpdate(hql,MD5Utils.text2md5(newPwd),userId);*/
        System.out.println("newPwd2--" + newPwd + "userId2---" + userId);
        userDao.executeUpdateByQueryName("updatePwd", MD5Utils.text2md5(newPwd), userId);
        //一定要在hbm.xml配置updatePwd

    }

    @Override
    public void save(User model, String[] roleIds) {
        //1.保存到t_user表
        userDao.save(model);
        //2.保存到activiti的act_id_user表
        org.activiti.engine.identity.User actUser= new UserEntity();
        actUser.setId(model.getId());
        identityService.saveUser(actUser);

//3.用户拥有角色
        for (String roleId : roleIds) {
            Role role=roleDao.findById(roleId);
            model.getRoles().add(role);

            //4.维护activiti的用户跟组的关系
            String userId = actUser.getId();
            String groupId = role.getName();
            identityService.createMembership(userId,groupId);
        }
    }

    @Override
    public void pageQuery(PageBean<User> pd) {
        userDao.pageQuery(pd);
    }

    @Override
    public void save(User entity) {
        userDao.save(entity);
    }

    @Override
    public void update(User entity) {
        userDao.update(entity);
    }

    @Override
    public void delete(User entity) {
        userDao.delete(entity);
    }

    @Override
    public User findById(Serializable id) {
        return userDao.findById(id);
    }

    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }
}
